package com.xjscrm.server.service.tasktagauto.impl;

import com.alibaba.fastjson.JSONObject;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.msg.*;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.OptEnum;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.operatorplandevice.OperatorPlanDeviceRule;
import com.xjscrm.common.vo.tasktagauto.EventRule;
import com.xjscrm.common.vo.tasktagauto.GroupSelect;
import com.xjscrm.server.common.util.DeviceTools;
import com.xjscrm.server.common.util.SleepTimeTools;
import com.xjscrm.server.mapper.*;
import com.xjscrm.server.service.customer.WwCustomerTagsService;
import com.xjscrm.server.service.tasktagauto.TaskTagAutoService;
import com.xjscrm.server.vo.device.Device;
import com.xjscrm.server.vo.tasktagauto.TaskTagAutoVerifyResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 企业微信群实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class TaskTagAutoServiceImpl implements TaskTagAutoService {

    @Autowired
    private WwGroupMapper wwGroupMapper;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private TaskTagAutoMapper taskTagAutoMapper;
    @Autowired
    private TaskTagAutoDeviceMapper taskTagAutoDeviceMapper;
    @Autowired
    private WwTagsMapper wwTagsMapper;
    @Autowired
    private WwCustomerMapper wwCustomerMapper;
    @Autowired
    private WwCustomerTagsService wwCustomerTagsService;
    @Autowired
    private WwCustomerBlacklistMapper wwCustomerBlacklistMapper;

    /**
     * 成员进群满足自动打标签任务
     *
     * @param micaTransDto
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void taskTagAutoForGroupMemberAdd(MicaTransDto micaTransDto) {
        try {
            log.info("--监控系统日志--开始--");


            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
                return;
            }

            //查询该机器人
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                return;
            }
            Device device = DeviceTools.transDevice(wwDevice);
            if (device == null) {
                return;
            }

            //更新时间
            int now = DateUtil.getTime();

            MicaGroupMemberAddMsg micaGroupMemberAddMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaGroupMemberAddMsg.class);

            if (micaGroupMemberAddMsg != null) {
                List<MicaGroupMemberItemMsg> members = micaGroupMemberAddMsg.getMembers();
                if (members == null || members.size() == 0) {
                    return;
                }
                //是否是客户
                List<WwCustomer> wwCustomerList = new ArrayList<>();
                for (MicaGroupMemberItemMsg member : members) {

                    //默认黑名单不通过
                    WwCustomerBlacklist wwCustomerBlacklist = wwCustomerBlacklistMapper.selectByWxid(micaTransDto.getMerId(), member.getWxid());
                    if(wwCustomerBlacklist != null){ //在黑名单中
                        continue;
                    }

                    WwCustomer wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(device.getDeviceUniqueId(), member.getWxid());
                    if(wwCustomer != null){
                        wwCustomerList.add(wwCustomer);
                    }
                }

                //表示未找到是会员的退群者，则不打标签
                if(wwCustomerList.size() == 0){
                    return;
                }

                //查询该业务下满足的自动打标签任务对于的标签列表
                List<TaskTagAutoVerifyResult> taskTagAutoVerifyResults = verifyParaGroupMemberAdd(micaGroupMemberAddMsg, device);
                //打标签
                if (taskTagAutoVerifyResults != null && taskTagAutoVerifyResults.size() > 0) {
                    for (TaskTagAutoVerifyResult taskTagAutoVerifyResult : taskTagAutoVerifyResults) {
                        //查询标签列表
                        List<Long> tagIdList = taskTagAutoVerifyResult.getTagIdList();
                        if (tagIdList != null && tagIdList.size() > 0) {
                            for (Long tagId : tagIdList) {
                                for (WwCustomer wwCustomer : wwCustomerList) {
                                    wwCustomerTagsService.addWwCustomerTag(device.getMerId(), wwCustomer, tagId, device);
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }finally {
            log.info("--监控系统日志--结束--");
        }
    }


    /**
     * 成员退群满足条件触发自动打标签功能
     *
     * @param micaTransDto
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void taskTagAutoForGroupMemberDel(MicaTransDto micaTransDto) {

        try {
            log.info("--监控系统日志--开始--");

            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
                return;
            }

            //查询该机器人
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                return;
            }
            Device device = DeviceTools.transDevice(wwDevice);
            if (device == null) {
                return;
            }

            //更新时间
            int now = DateUtil.getTime();

            MicaGroupMemberDelMsg micaGroupMemberDelMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaGroupMemberDelMsg.class);

            if (micaGroupMemberDelMsg != null) {
                List<MicaGroupMemberItemMsg> members = micaGroupMemberDelMsg.getMembers();
                if (members == null || members.size() == 0) {
                    return;
                }

                //是否是客户
                List<WwCustomer> wwCustomerList = new ArrayList<>();
                for (MicaGroupMemberItemMsg member : members) {
                    WwCustomer wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(device.getDeviceUniqueId(), member.getWxid());
                    if(wwCustomer != null){
                        wwCustomerList.add(wwCustomer);
                    }
                }

                //查询该业务下满足的自动打标签任务对于的标签列表
                List<TaskTagAutoVerifyResult> taskTagAutoVerifyResults = verifyParaGroupMemberDel(micaGroupMemberDelMsg, device);
                //打标签
                if (taskTagAutoVerifyResults != null && taskTagAutoVerifyResults.size() > 0) {
                    for (TaskTagAutoVerifyResult taskTagAutoVerifyResult : taskTagAutoVerifyResults) {
                        //查询标签列表
                        List<Long> tagIdList = taskTagAutoVerifyResult.getTagIdList();
                        if (tagIdList != null && tagIdList.size() > 0) {
                            for (Long tagId : tagIdList) {
                                for (WwCustomer wwCustomer : wwCustomerList) {
                                    wwCustomerTagsService.addWwCustomerTag(device.getMerId(), wwCustomer, tagId, device);
                                }
                            }
                        }
                    }
                }
            }

        }catch (Exception e){

        }finally {
            log.info("--监控系统日志--结束--");
        }

    }

    /**
     * 客户进群验证
     * eventTrigger
     * @param micaGroupMemberAddMsg
     * @return 实例对象
     */
    private List<TaskTagAutoVerifyResult> verifyParaGroupMemberAdd(MicaGroupMemberAddMsg micaGroupMemberAddMsg, Device device) {

        List<TaskTagAutoVerifyResult> taskTagAutoVerifyResults = new ArrayList<>();

        try {
            if (device == null) {
                return taskTagAutoVerifyResults;
            }

            if (micaGroupMemberAddMsg == null) {
                return taskTagAutoVerifyResults;
            }

            //群wxid
            String groupId = micaGroupMemberAddMsg.getGroupId();
            //群昵称
            String groupName = micaGroupMemberAddMsg.getGroupName();

            //自动任务中配置的类型（0-客户进群，1-客户退群，2-群封禁）
            Integer eventTrigger = 0;

            //查询该运营商所配置事件触发的自动打标签任务(触发类型(1-条件触发;2-事件触发))
            List<TaskTagAuto> taskTagAutos = taskTagAutoMapper.selectByParaType(device.getMerId(), 2);
            if (taskTagAutos != null && taskTagAutos.size() > 0) {
                for (TaskTagAuto taskTagAuto : taskTagAutos) {
                    EventRule eventRule = JSONObject.parseObject(taskTagAuto.getEventRule(), EventRule.class);
                    //事件规则不等于null
                    if (eventRule != null) {
                        //是否符合事件类型
                        boolean eventTriggerFlag = false;
                        if (Tools.getInteger(eventRule.getConditionType()).intValue() == eventTrigger.intValue()) {
                            eventTriggerFlag = true;
                        }
                        //符合群
                        boolean groupWxidFlag = false;
                        String opt = eventRule.getOpt();
                        List<GroupSelect> groupSelectList = eventRule.getGroupSelectList();
                        if (groupSelectList != null && groupSelectList.size() > 0) {
                            if (OptEnum.EQ.getValue().equals(opt)) { //等于
                                //去列表中查询该机器人的群选择对象
                                GroupSelect groupSelect = groupSelectList.stream().filter(item -> Objects.equals(device.getDeviceId(), item.getDeviceId())).findFirst().orElse(null);
                                if (groupSelect != null) {
                                    List<String> groupWxidList = groupSelect.getGroupWxidList();
                                    if (groupWxidList != null) {
                                        //该机器人下是否配置了该群wxid
                                        if (groupWxidList.contains(groupId)) {//包含群wxid
                                            groupWxidFlag = true;
                                        }
                                    }
                                }
                            } else if (OptEnum.NQ.getValue().equals(opt)) {//不等于此群
                                //去列表中查询该机器人的群选择对象
                                GroupSelect groupSelect = groupSelectList.stream().filter(item -> Objects.equals(device.getDeviceId(), item.getDeviceId())).findFirst().orElse(null);
                                if (groupSelect != null) {//找到了该机器人的群配置，还得再去严重是否不包含在群列表中
                                    List<String> groupWxidList = groupSelect.getGroupWxidList();
                                    if (groupWxidList != null) {
                                        //该机器人下是否配置了该群wxid
                                        if (!groupWxidList.contains(groupId)) {//不包含群wxid
                                            groupWxidFlag = true;
                                        }
                                    } else {//该机器人未配置群列表
                                        groupWxidFlag = true;
                                    }
                                } else { //未找到该机器人的群选择，则表示符合
                                    groupWxidFlag = true;
                                }
                            }

                            //事件和群都符合条件，则封装标签
                            if (eventTriggerFlag && groupWxidFlag) {
                                //全部机器人时，符合每个机器人打标签，封装标签
                                if (taskTagAuto.getEnterpriseType() != null
                                        && taskTagAuto.getEnterpriseType().intValue() == 0) {   //全部机器人
                                    //查询关联机器人表，判断是否有休眠时间
                                    TaskTagAutoDevice taskTagAutoDevice = taskTagAutoDeviceMapper.selectByTaskIdAndDeviceUniqueId(taskTagAuto.getId(), device.getDeviceUniqueId());
                                    if(taskTagAutoDevice != null){//则表示有休眠时间
                                        OperatorPlanDeviceRule operatorPlanDeviceRule = JSONObject.parseObject(taskTagAutoDevice.getRule(), OperatorPlanDeviceRule.class);
                                        //此时属于休眠时间
                                        boolean sleepTimeFlag = SleepTimeTools.verifySleepTime(operatorPlanDeviceRule);
                                        if(sleepTimeFlag){
                                            continue;
                                        }
                                    }
                                    //获取配置的企业标签列表
                                    List<Long> tagIdList = JSONObject.parseArray(taskTagAuto.getEnterpriseTags(), Long.class);
                                    if (tagIdList != null && tagIdList.size() > 0) {
                                        TaskTagAutoVerifyResult taskTagAutoVerifyResult = new TaskTagAutoVerifyResult();
                                        taskTagAutoVerifyResult.setTaskId(taskTagAuto.getId());
                                        taskTagAutoVerifyResult.setType(1); //企微标签
                                        taskTagAutoVerifyResult.setTagIdList(tagIdList);
                                        taskTagAutoVerifyResults.add(taskTagAutoVerifyResult);
                                    }
                                } else { //部分机器人
                                    TaskTagAutoDevice taskTagAutoDevice = taskTagAutoDeviceMapper.selectByTaskIdAndDeviceUniqueId(taskTagAuto.getId(), device.getDeviceUniqueId());
                                    if (taskTagAutoDevice != null) { //查询到机器人有符合的配置，则封装标签

                                        OperatorPlanDeviceRule operatorPlanDeviceRule = JSONObject.parseObject(taskTagAutoDevice.getRule(), OperatorPlanDeviceRule.class);
                                        //此时属于休眠时间
                                        boolean sleepTimeFlag = SleepTimeTools.verifySleepTime(operatorPlanDeviceRule);
                                        if(sleepTimeFlag){
                                            continue;
                                        }
                                        //企微标签
                                        if (Tools.getInteger(taskTagAuto.getTagType()).intValue() == 1) {//企微标签从主表中获取
                                            //获取配置的企业标签列表
                                            List<Long> tagIdList = JSONObject.parseArray(taskTagAuto.getEnterpriseTags(), Long.class);
                                            if (tagIdList != null && tagIdList.size() > 0) {
                                                TaskTagAutoVerifyResult taskTagAutoVerifyResult = new TaskTagAutoVerifyResult();
                                                taskTagAutoVerifyResult.setTaskId(taskTagAuto.getId());
                                                taskTagAutoVerifyResult.setType(1); //企微标签
                                                taskTagAutoVerifyResult.setTagIdList(tagIdList);
                                                taskTagAutoVerifyResults.add(taskTagAutoVerifyResult);
                                            }
                                        } else {//个人标签
                                            //获取配置的企业标签列表
                                            List<Long> tagIdList = JSONObject.parseArray(taskTagAutoDevice.getPrivateTags(), Long.class);
                                            if (tagIdList != null && tagIdList.size() > 0) {
                                                TaskTagAutoVerifyResult taskTagAutoVerifyResult = new TaskTagAutoVerifyResult();
                                                taskTagAutoVerifyResult.setTaskId(taskTagAuto.getId());
                                                taskTagAutoVerifyResult.setType(2); //个人标签
                                                taskTagAutoVerifyResult.setTagIdList(tagIdList);
                                                taskTagAutoVerifyResults.add(taskTagAutoVerifyResult);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }

        return taskTagAutoVerifyResults;
    }


    /**
     * 客户退群验证
     * eventTrigger
     * @param micaGroupMemberDelMsg
     * @return 实例对象
     */
    private List<TaskTagAutoVerifyResult> verifyParaGroupMemberDel(MicaGroupMemberDelMsg micaGroupMemberDelMsg, Device device) {

        List<TaskTagAutoVerifyResult> taskTagAutoVerifyResults = new ArrayList<>();

        if (device == null) {
            return taskTagAutoVerifyResults;
        }

        if (micaGroupMemberDelMsg == null) {
            return taskTagAutoVerifyResults;
        }

        //群wxid
        String groupId = micaGroupMemberDelMsg.getGroupId();
        //群昵称
        String groupName = micaGroupMemberDelMsg.getGroupName();

        //自动任务中配置的类型（0-客户进群，1-客户退群，2-群封禁）
        Integer eventTrigger = 1;

        //查询该运营商所配置事件触发的自动打标签任务
        List<TaskTagAuto> taskTagAutos = taskTagAutoMapper.selectByParaType(device.getMerId(), 2);
        if (taskTagAutos != null && taskTagAutos.size() > 0) {
            for (TaskTagAuto taskTagAuto : taskTagAutos) {
                EventRule eventRule = JSONObject.parseObject(taskTagAuto.getEventRule(), EventRule.class);
                //事件规则不等于null
                if (eventRule != null) {
                    //是否符合事件类型
                    boolean eventTriggerFlag = false;
                    if (Tools.getInteger(eventRule.getConditionType()).intValue() == eventTrigger.intValue()) {
                        eventTriggerFlag = true;
                    }
                    //符合群
                    boolean groupWxidFlag = false;
                    String opt = eventRule.getOpt();
                    List<GroupSelect> groupSelectList = eventRule.getGroupSelectList();
                    if (groupSelectList != null && groupSelectList.size() > 0) {
                        if (OptEnum.EQ.getValue().equals(opt)) { //等于
                            //去列表中查询该机器人的群选择对象
                            GroupSelect groupSelect = groupSelectList.stream().filter(item -> Objects.equals(device.getDeviceId(), item.getDeviceId())).findFirst().orElse(null);
                            if (groupSelect != null) {
                                List<String> groupWxidList = groupSelect.getGroupWxidList();
                                if (groupWxidList != null) {
                                    //该机器人下是否配置了该群wxid
                                    if (groupWxidList.contains(groupId)) {//包含群wxid
                                        groupWxidFlag = true;
                                    }
                                }
                            }
                        } else if (OptEnum.NQ.getValue().equals(opt)) {//不等于此群
                            //去列表中查询该机器人的群选择对象
                            GroupSelect groupSelect = groupSelectList.stream().filter(item -> Objects.equals(device.getDeviceId(), item.getDeviceId())).findFirst().orElse(null);
                            if (groupSelect != null) {//找到了该机器人的群配置，还得再去严重是否不包含在群列表中
                                List<String> groupWxidList = groupSelect.getGroupWxidList();
                                if (groupWxidList != null) {
                                    //该机器人下是否配置了该群wxid
                                    if (!groupWxidList.contains(groupId)) {//不包含群wxid
                                        groupWxidFlag = true;
                                    }
                                } else {//该机器人未配置群列表
                                    groupWxidFlag = true;
                                }
                            } else { //未找到该机器人的群选择，则表示符合
                                groupWxidFlag = true;
                            }
                        }

                        //事件和群都符合条件，则封装标签
                        if (eventTriggerFlag && groupWxidFlag) {
                            //全部机器人时，符合每个机器人打标签，封装标签
                            if (taskTagAuto.getEnterpriseType() != null
                                    && taskTagAuto.getEnterpriseType().intValue() == 0) {   //全部机器人,只有企业标签
                                //查询关联机器人表，判断是否有休眠时间
                                TaskTagAutoDevice taskTagAutoDevice = taskTagAutoDeviceMapper.selectByTaskIdAndDeviceUniqueId(taskTagAuto.getId(), device.getDeviceUniqueId());
                                if(taskTagAutoDevice != null){//则表示有休眠时间
                                    OperatorPlanDeviceRule operatorPlanDeviceRule = JSONObject.parseObject(taskTagAutoDevice.getRule(), OperatorPlanDeviceRule.class);
                                    //此时属于休眠时间
                                    boolean sleepTimeFlag = SleepTimeTools.verifySleepTime(operatorPlanDeviceRule);
                                    if(sleepTimeFlag){
                                        continue;
                                    }
                                }

                                //获取配置的企业标签列表
                                List<Long> tagIdList = JSONObject.parseArray(taskTagAuto.getEnterpriseTags(), Long.class);
                                if (tagIdList != null && tagIdList.size() > 0) {
                                    TaskTagAutoVerifyResult taskTagAutoVerifyResult = new TaskTagAutoVerifyResult();
                                    taskTagAutoVerifyResult.setTaskId(taskTagAuto.getId());
                                    taskTagAutoVerifyResult.setType(1); //企微标签
                                    taskTagAutoVerifyResult.setTagIdList(tagIdList);
                                    taskTagAutoVerifyResults.add(taskTagAutoVerifyResult);
                                }

                            } else { //部分机器人。可以是企业标签或者个人标签
                                TaskTagAutoDevice taskTagAutoDevice = taskTagAutoDeviceMapper.selectByTaskIdAndDeviceUniqueId(taskTagAuto.getId(), device.getDeviceUniqueId());
                                if (taskTagAutoDevice != null) { //查询到机器人有符合的配置，则封装标签

                                    OperatorPlanDeviceRule operatorPlanDeviceRule = JSONObject.parseObject(taskTagAutoDevice.getRule(), OperatorPlanDeviceRule.class);
                                    //此时属于休眠时间
                                    boolean sleepTimeFlag = SleepTimeTools.verifySleepTime(operatorPlanDeviceRule);
                                    if(sleepTimeFlag){
                                        continue;
                                    }

                                    //企微标签
                                    if (Tools.getInteger(taskTagAuto.getTagType()).intValue() == 1) {//企微标签从主表中获取
                                        //获取配置的企业标签列表
                                        List<Long> tagIdList = JSONObject.parseArray(taskTagAuto.getEnterpriseTags(), Long.class);
                                        if (tagIdList != null && tagIdList.size() > 0) {
                                            TaskTagAutoVerifyResult taskTagAutoVerifyResult = new TaskTagAutoVerifyResult();
                                            taskTagAutoVerifyResult.setTaskId(taskTagAuto.getId());
                                            taskTagAutoVerifyResult.setType(1); //企微标签
                                            taskTagAutoVerifyResult.setTagIdList(tagIdList);
                                            taskTagAutoVerifyResults.add(taskTagAutoVerifyResult);
                                        }
                                    } else {//个人标签
                                        //获取配置的企业标签列表
                                        List<Long> tagIdList = JSONObject.parseArray(taskTagAutoDevice.getPrivateTags(), Long.class);
                                        if (tagIdList != null && tagIdList.size() > 0) {
                                            TaskTagAutoVerifyResult taskTagAutoVerifyResult = new TaskTagAutoVerifyResult();
                                            taskTagAutoVerifyResult.setTaskId(taskTagAuto.getId());
                                            taskTagAutoVerifyResult.setType(2); //个人标签
                                            taskTagAutoVerifyResult.setTagIdList(tagIdList);
                                            taskTagAutoVerifyResults.add(taskTagAutoVerifyResult);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return taskTagAutoVerifyResults;
    }

}
